package com.mojo.jedis.controller;

import com.mojo.jedis.CacheConstant;
import com.mojo.jedis.service.RedisLockService;
import com.mojo.jedis.service.UserService;
import com.mojo.jedis.pojo.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.UUID;

/**
 * spring cache常用注解
 * <p>
 * {@link org.springframework.cache.annotation.Cacheable}
 * {@link org.springframework.cache.annotation.CachePut}
 * {@link org.springframework.cache.annotation.CacheEvict}
 * 三个接口注解
 *
 * @author <a href="mailto:sjj@jianzhimao.com">mojo</a>
 * copyright (C), 2013-2023, 广州九尾信息科技有限公司
 * @date 2023/3/8 11:22
 */
@RestController
@RequestMapping("cache")
public class SpringCacheController {
    private static final Logger logger = LoggerFactory.getLogger(SpringCacheController.class);
    @Autowired
    private UserService userService;
    @Autowired
    private RedisLockService redisLockService;

    // @Cacheable注解，默认先查询缓存,常用于查询的方法上
    @GetMapping("user/cacheable/{id}")
    @Cacheable(value = CacheConstant.REDIS_KEY_DATABASE, key = "'" + CacheConstant.USER_CACHE_PREFIX + "' + #id", unless = "#result == null")
    public User cacheable(@PathVariable Integer id) {
        logger.info("查询用户:{}", id);
        return userService.findById(id);
    }

    // @CachePut注解，每次执行将会缓存方法的返回结果，常用于新增接口
    @PostMapping("user/cacheput")
    @CachePut(value = CacheConstant.REDIS_KEY_DATABASE, key = "'" + CacheConstant.USER_CACHE_PREFIX + "'+#user.getName()", condition = "#result!=null")
    public User cachePut(@RequestBody User user) {
        logger.info("新增用户，user:{}", user);
        return userService.add(user);
    }

    // @CacheEvict注解，清空缓存
    @PutMapping("user/cacheEvict")
    @CacheEvict(value = CacheConstant.REDIS_KEY_DATABASE, key = "'" + CacheConstant.USER_CACHE_PREFIX + "'+#user.getName()")
    public void CacheEvict(@RequestBody User user) {
        logger.info("更新用户，user:{}", user);
    }

    @GetMapping("lock")
    public void redisLock() {
        String key = UUID.randomUUID().toString();
        for (int i = 0; i < 10; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    redisLockService.lock(key);
                    try {
                        Thread.sleep(3000L);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    logger.info("当前时间：{}", LocalDateTime.now());
                    redisLockService.unlock(key);
                }
            }).start();
        }
    }
}
